﻿#!usr/lib/python
#-*- coding:utf-8 -*-
#=======================
#@author:jeffxun
#@date:2013-02-16
#=======================

import urllib
import httplib

class __CLinkHttp:
    """ """
    def __init__(self,url,port=None):
        """ 
        如果url 形如:http://xx.xx.x.x:400 那么port参数不要传入，会根据url自动赋值
        默认port 为80
        """
        self.__url      =   self.__fmturl__(url)
        self.__body     =   ""
        self.__header   =   {}
        self.__urlbody  =   ""
        self.__path     =   ""
        self.__http =   httplib.HTTPConnection(self.urlHost(url),port)
        self.__http.connect()
        
    def __fmturl__(self,url):
        """ """
        start   = "http://"
        if not str(url).startswith(start):
            url = start + url
        return url
        
    def urlHost(self,url):
        """ """
        splitres =  httplib.urlsplit(url)
        return splitres.netloc
    
    def urlPath(self,url):
        """ """
        splitres =  httplib.urlsplit(url)
        return splitres.path
        
    def setBody(self,data=None):
        """ 
        传入参数，有些是将参数直接放在url里面，这里就不能使用
        """         
        if data:
            assert isinstance(data,dict);
            data = urllib.quote(data.decode(sys.stdin.encoding).encode('utf-8'))
            print data
            self.__body = urllib.urlencode(data)
        
    def setUrlBody(self,data=None):
        """ 
        放在url后面直接使用的参数，不通过body传送的        
        """
        if data:
            assert isinstance(data,dict);
            self.__urlbody  = urllib.urlencode(data)

    def setUrlPath(self,path=None):
        """
        url的访问位置
        """         
        if  path:
            self.__path = self.urlPath(path)  
            if not self.__path.startswith("/"):
                self.__path = "/" + self.__path;
            if self.__path.endswith("/"):
                self.__path = self.__path[:-1]
            
    def setHeader(self,data=None):
        """ 
        url 头        
        """
        if not data:
            self.__header.clear()
        else:
            assert isinstance(data,dict)
            self.__header = data
    
    def request(self,method="GET"):
        """ """
        url = self.__url
        if self.__path:
            url += self.__path
        if self.__urlbody:
            url += "?"+self.__urlbody
        print url
        self.__http.request(method,url,body=self.__body,headers=self.__header)    
        res = self.__http.getresponse()
        return res
        
def httpLink(url,port=None,method="GET",path=None,urlbody=None,body=None,header=None):
    """ """
    http = __CLinkHttp(url,port)
    http.setUrlPath(path)
    http.setUrlBody(urlbody)
    http.setBody(body)
    http.setHeader(header)
    return http.request(method)
    
def urlHost(url):
    host = httplib.urlsplit(url).netloc;
    if host.find(":") != -1:
        host = host[:host.find(":")]
    return host
    
def urlHostPort(url):
    port = 80
    host = httplib.urlsplit(url).netloc;
    if host.find(":") == -1:
        host += ":%s"%port
    return host

class HttpWebServer(object):
    """HttpWebServer"""
    def __init__(self,url,urlData = None):
        """ """
        self.__url = self.__geturl__(url,urlData)

    def __geturl__(self,url,data):
        if isinstance(data,dict):
            body =urllib.urlencode(data)
        fulurl = url + '?' + body
        return fulurl

    def httpconnect(self,method='Get',port=80):
        self.conn =  httplib.HTTPConnection(urlHostPort(self.__url))
        self.conn.connect();
        self.conn.putrequest("GET", self.__url, None)
        #self.conn.putheader("Content-Length", 0)
        #self.conn.putheader("Connection", "close")
        
        #self.conn.putheader("Accept-Language", "zh-CN")
        #self.conn.putheader("Accept-Encoding", "gzip, deflate")
        self.conn.endheaders()
        #self.conn.request("GET",self.__url);
        res = self.conn.getresponse()
        result =  res.read(res.length)
        return result
        
    def checkResult(self,data):
        result = r"<result>"
        role_exist = r"<role_exist>"
        try:
            index = len(result)
            role  = (index+1)*2+len(role_exist)
            result= int(data[index:index+1])
            role_exist= int(data[role+1:role+2])
            #print result,role_exist
            if result != 1:
                return -1
            if role_exist != 1:
                return -2
            return 1
        except:
            return 0
        
    def __del__(self):
        try:
            self.conn.close()
        except:
            pass
    
#url = "http://192.168.1.44/entry/login"
#data = {"username":"huox01",
#        "passwd":"e10adc3949ba59abbe56e057f20f883e",
#        "servid":"hx01"}
#
#res = httpLink(url,urlbody=data)
#print res.read()
if __name__ == "__main__":
    host ="http://192.168.1.44/entry/login"
    print urlHostPort(host);
    data = {"username":"huox01",
            "passwd":"e10adc3949ba59abbe56e057f20f883e",
            "servid":"hx01"}
#
    http = HttpWebServer(host,data)
    print http.httpconnect()